package com.apadog.study.test;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.apadog.study.utils.PlaywrightSingleton;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.Cookie;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

@Slf4j
public class H5Login {



    private static final String COOKIE_FILE = "jsessionid.txt";


    public String refreshCookie() {
        Playwright playwright = PlaywrightSingleton.get();
        Page page;
        try (Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
                .setHeadless(false))) {
            page = browser.newPage();

            // 1. 打开目标网站
            page.navigate("https://channel.hodo170.com/ChannelWeb/"); // 你要访问的 URL
            String cookie = this.checkCookie(page);
            log.info("登入获取到cookie:{}",cookie);
            saveJsesssionIdToFile(cookie);
            log.info("刷新本地cookie:{}",cookie);

            return cookie;
        }catch (Exception e){
            throw new RuntimeException("浏览器获取cookie异常：" + e.getMessage());
        }finally {
            playwright.close();
        }

    }

    public String getCookie(){
        String cookie;
        Path path = Paths.get(COOKIE_FILE);
        if (Files.exists(path)) {
            cookie = readJsesssionIdFromFile();
            log.info("读取文件获取到cookie:{}",cookie);
            if(StringUtils.isBlank(cookie)){
                cookie = this.refreshCookie();
            }
        }else{
            cookie = this.refreshCookie();
        }

        if(StringUtils.isBlank(cookie)){
            throw new RuntimeException("cookie为空");
        }
        return cookie;
    }

    private static String readJsesssionIdFromFile() {
        Path path = Paths.get(COOKIE_FILE);
        if (Files.exists(path)) {
            try {
                String content = Files.readString(path).trim();
                if (!content.isEmpty()) {
                    return content;
                }
            } catch (IOException e) {
                throw new RuntimeException("JSESSIONID 保存本地文件异常");
            }
        }
        return null;
    }

    private static void saveJsesssionIdToFile(String jsessionId) {
        try {
            Files.writeString(Paths.get(COOKIE_FILE), jsessionId);
            log.info("JSESSIONID 已保存到本地文件。");
        } catch (IOException e) {
            throw new RuntimeException("JSESSIONID 保存本地文件异常");
        }
    }


    private String checkCookie(Page page){
        page.waitForTimeout(2000); // 每秒检查一次
        Locator target = page.locator("body > div.top > div > div.home"); // 更换为你的目标选择器
        log.info("暂未登入----请在浏览器输入账号，密码，验证码先登入");
        if (target.count() > 0 && target.isVisible()) {
            BrowserContext context = page.context();
            List<Cookie> cookies = context.cookies();
            String JSESSIONID = null;
            //log.info("cookies:{}",cookies);
            for (Cookie cookie : cookies) {
                //log.info("{}={}",cookie.name,cookie.value);
                if ("JSESSIONID".equals(cookie.name)) {
                    JSESSIONID = StrUtil.format("JSESSIONID={}",cookie.value);
                    break;
                }
            }
            if(StringUtils.isBlank(JSESSIONID)){
                throw new RuntimeException("为获取到cookie里面的 JSESSIONID");
            }
            return JSESSIONID;
        }else {
            //log.info("登入成功");
            return this.checkCookie(page);
        }
    }

}
